package com.cloudpan;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.apache.http.entity.FileEntity;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xslf.usermodel.*;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.librealsense.frame;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author sc
 * @DATE 2024/1/19 14:06
 * @Description:
 * @Version 1.0
 */
public class PictureUtil {

    @Test
    public void test(){
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            FileInputStream fileInputStream = new FileInputStream("F:\\cache\\522233014杨明珠.pptx");
            inputStream = getThumbnailPPT(fileInputStream);
            String filepath = "F:/cache/" + "222333.png";
            byte[] bytes = new byte[1024];
            fileOutputStream = new FileOutputStream(filepath);
            int len;
            while ((len = inputStream.read(bytes)) > 0){
                fileOutputStream.write(bytes,0,len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取pdf缩略图
    public InputStream getThumbnailPDF(FileInputStream inputStream){
        PDDocument pdfDocument = null;
        try {
            //PDDocument类的load()方法用于加载现有PDF文档
            pdfDocument = PDDocument.load(inputStream);
            //PDFRenderer的类将PDF文档呈现为AWT BufferedImage
            PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);
            // 提取的页码
            int pageNumber = 0;
            // 以50 dpi 读取存入 BufferedImage 对象
            int dpi = 50;
            //Renderer类的renderImage()方法在特定页面中渲染图像
            BufferedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
            // 文件类型转换
            InputStream result = bufferedImageToInputStream(buffImage);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭文档
            if(pdfDocument != null){
                try {
                    pdfDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //获取ppt缩略图
    public InputStream getThumbnailPPT(InputStream inputStream) throws Exception {
        int imgCount = 0;
        BufferedImage img = null;
        try {
            XMLSlideShow xmlSlideShow = new XMLSlideShow(inputStream);
            // 获取大小
            Dimension pgsize = xmlSlideShow.getPageSize();
            // 获取幻灯片
            XSLFSlide[] slides = xmlSlideShow.getSlides().toArray(new XSLFSlide[0]);
            imgCount = slides.length;
            XSLFSlide slide = slides[0];
            XSLFShape[] xslfShapes = slide.getShapes().toArray(new XSLFShape[0]);
            for (XSLFShape shape : xslfShapes) {
                if (shape instanceof XSLFTextShape) {
                    XSLFTextShape sh = (XSLFTextShape) shape;
                    List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                    for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                        List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                        for (XSLFTextRun xslfTextRun : textRuns) {
                            xslfTextRun.setFontFamily("宋体");
                        }
                    }
                }
                // 创建BufferedImage对象，图像的尺寸为原来的每页的尺寸*倍数times
                img = new BufferedImage(880, 480, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,pgsize.height));
                // 最核心的代码
                slides[0].draw(graphics);
            }
            InputStream result = bufferedImageToInputStream(img);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("PPT转换成图片 发生异常！");
        }
        return null;
    }
    //获取图片类的缩略图
    public InputStream getThumbnailPhoto(FileInputStream inputStream){
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = Thumbnails.of(inputStream)
                    .size(680, 480)
                    .outputQuality(0.4f).asBufferedImage();
            InputStream result = bufferedImageToInputStream(bufferedImage);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取视频的缩略图
    public InputStream getThumbnailVideo(FileInputStream inputStream) {
        //Frame对象
        Frame frame = null;
        FFmpegFrameGrabber fFmpegFrameGrabber = null;
        //标识
        int flag = 0;
        try {
            fFmpegFrameGrabber = new FFmpegFrameGrabber(inputStream);
            fFmpegFrameGrabber.start();
            //获取视频总帧数
            int ftp = fFmpegFrameGrabber.getLengthInFrames();
            //System.out.println("时长 " + ftp / fFmpegFrameGrabber.getFrameRate() / 60);
            while (flag <= ftp) {
                frame = fFmpegFrameGrabber.grabImage();
                //对视频的第五帧进行处理
                if (frame != null && flag == 5) {
                    //文件转换
                    BufferedImage bufferedImage = FrameToBufferedImage(frame);
                    try {
                        System.out.println("生成中");
                        BufferedImage image = Thumbnails.of(bufferedImage).size(680, 480).asBufferedImage();
                        InputStream inputStream1 = bufferedImageToInputStream(image);
                        System.out.println("生成完成");
                        return inputStream1;
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
                flag++;
            }
            fFmpegFrameGrabber.close();
        } catch (Exception E) {
            E.printStackTrace();
        }finally {
            if (fFmpegFrameGrabber != null){
                try {
                    fFmpegFrameGrabber.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (frame != null){
                try {
                    frame.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    //bufferedImageToInputStream 转换
    public InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //创建BufferedImage对象
    public BufferedImage FrameToBufferedImage(Frame frame) {
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }

    public String getThumbnailPath(String uuid){
        return "thumbnail/" + uuid + ".png";
    }

}
